// 获取用户文集下的所有文章
import pool from '@/server/db'
import { RowDataPacket } from 'mysql2'
import joi from 'joi'

const schema = joi.object({
  notebookID: joi.number().required(),
  pageSize: joi.string().required(),
  page: joi.string().required(),
})

export default defineEventHandler(async event => {
  // get方法只能传字符串类型的参数，getQuery方法返回的对象中的键值对也是字符串类型的
  interface QueryParams {
    notebookID: string
    pageSize: string
    page: string
  }
  const query: QueryParams = await getQuery(event)

  // 判断用户是否登录
  if (!event.context.userinfo) return r('请登录')
  const { uid } = event.context.userinfo

  // 数据校验
  try {
    schema.validate(query)
  } catch (error) {
    return r('数据校验错误 ' + error)
  }

  // 查询文章
  try {
    const { pageSize, page, notebookID } = query
    const offset = Number(pageSize) * (Number(page) - 1)
    const [notesIdRows] = await pool.query(
      'SELECT `note_id` FROM `notebook_notes` WHERE `notebook_id` = ?',
      [notebookID]
    )

    const noteIdArr = (notesIdRows as RowDataPacket[]).map(
      (item: RowDataPacket) => item.note_id
    )

    const [notesRows] = await pool.query(
      'SELECT * FROM `notes` WHERE `uid` = ? AND `id` IN (?)',
      [uid, noteIdArr]
    )
    return r('查询成功', 1, notesRows)
  } catch (error) {
    return r('文章查询错误:' + error)
  }
})
